/* Copyright 2009 Anthony Surma
This file is part of Java's Kademlia Extension (JKADX).

JKADX is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.

JKADX is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with JKADX.  If not, see <http://www.gnu.org/licenses/>.
 */

package jkadx.xml;

import org.jdom.*;
import java.io.FileOutputStream;
import org.jdom.output.XMLOutputter;
import java.io.IOException;
import java.io.File;
import org.jdom.input.SAXBuilder;
import java.util.ArrayList;
import java.util.List;

//if I extend Document, I can do this more elegantly --- maybe
public final class XML
{
    private XML() {}

    public static void saveToFile(File settingsFile, Document doc)
    {
        try {
            FileOutputStream out = new FileOutputStream(settingsFile);
            new XMLOutputter().output(doc, out);
            out.flush();
            out.close();
        } catch (IOException e) {
            System.err.println(e);
        }
    }

    public static Document loadFromFile(File file)
    {
        Document     document = null;
        SAXBuilder saxbuilder = new SAXBuilder();

        try {
            document = saxbuilder.build(file);
        } catch (JDOMException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    return document;
    }

    public static ArrayList<ElementNode> toArrayList(Document document)
    {
        Element                 readRoot = document.getRootElement();
        List                        list = readRoot.getChildren();
        ArrayList<ElementNode> arraylist = new ArrayList<ElementNode>();
        Element element;

        for (Object obj : list)
        {
            element = (Element)obj;
            arraylist.add(new ElementNode(element.getName(), element.getText()));
        }
    return arraylist;
    }
}